<template>
  <div class="contract-review">
    <!-- 审查结果展示区域 -->
    <div class="review-results">
      <div v-for="(item, index) in reviewItems" :key="index" class="review-item">
        <div class="review-header" @click="toggleReviewItem(index)">
          <div class="review-title">
            <span>{{ item.title }}</span>
            <el-tag :type="getStatusType(item.status)" size="small">{{ getStatusText(item.status) }}</el-tag>
          </div>
          <div class="review-actions">
            <i :class="item.expanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="item.status === 'loading'" class="review-loading">
          <el-progress type="circle" :percentage="item.progress" :width="80"></el-progress>
          <span class="loading-text">正在分析中...</span>
        </div>

        <!-- 审查结果内容 -->
        <div v-if="item.expanded && item.status === 'completed'" class="review-content">
          <div v-for="(result, rIndex) in item.results" :key="rIndex" class="review-detail">
            <div class="risk-level" :class="getRiskLevelClass(result.riskLevel)">
              {{ result.riskLevel }}
            </div>
            <div class="risk-content">
              <div class="risk-title">{{ result.title }}</div>
              <div class="risk-description">{{ result.description }}</div>
              <div class="risk-suggestion">
                <span class="label">修改建议：</span>
                <span class="text">{{ result.suggestion }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 错误状态 -->
        <div v-if="item.status === 'error'" class="review-error">
          <i class="el-icon-warning"></i>
          <span>{{ item.error }}</span>
          <el-button type="text" @click="retryReview(index)">重试</el-button>
        </div>
      </div>
    </div>

    <!-- 开始审查按钮 -->
    <div class="review-actions">
      <el-button type="primary" :loading="isReviewing" @click="startReview">
        {{ isReviewing ? '审查中...' : '开始审查' }}
      </el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ContractReview',
  data() {
    return {
      isReviewing: false,
      reviewItems: [
        {
          id: '1111729659573501955',
          title: '在合同整体中，身份与联系信息确认审查',
          status: 'pending', // pending, loading, completed, error
          progress: 0,
          expanded: false,
          results: [],
          error: null
        },
        {
          id: '1111729659573501956',
          title: '工作岗位条款审查',
          status: 'pending',
          progress: 0,
          expanded: false,
          results: [],
          error: null
        },
        {
          id: '1111729659573501957',
          title: '在合同主体条款中，主体信息是否完整、准确，是否具备主体资格',
          status: 'pending',
          progress: 0,
          expanded: false,
          results: [],
          error: null
        }
        // 可以添加更多审查项
      ],
      progressIntervals: {} // 存储进度条定时器
    }
  },
  methods: {
    // 开始审查
    async startReview() {
      if (this.isReviewing) return;
      this.isReviewing = true;

      // 重置所有项的状态
      this.reviewItems.forEach(item => {
        item.status = 'loading';
        item.progress = 0;
        item.results = [];
        item.error = null;
        this.startProgressSimulation(item);
      });

      // 获取路由参数
      const { fileUrl } = this.$route.query;
      const standpoint = this.$route.query.standpoint || '甲方'; // 从路由或其他地方获取
      const reviewScale = this.$route.query.reviewScale || '强'; // 从路由或其他地方获取

      // 创建审查请求
      const requests = this.reviewItems.map(item => this.checkContract(item, {
        fileUrl,
        userId: localStorage.getItem('userId') || 'abc-1244',
        standpoint,
        reviewScale,
        riskId: item.id
      }));

      // 并行执行所有请求
      Promise.allSettled(requests).finally(() => {
        this.isReviewing = false;
      });
    },

    // 单个合同审查请求
    async checkContract(item, params) {


      const uploadInstance = axios.create({
        baseURL: 'http://localhost:8481',
        timeout: 0,  // 0表示无超时限制
        headers: {
          Authorization: 'Bearer ' + (localStorage.getItem("token") || Store.state.token)
        }
      });
      try {
        const response = await uploadInstance.post('/api/files/checkContract', params, {
          timeout: 600000 // 10分钟超时
        });

        if (response.data.code === 0) {
          item.status = 'completed';
          item.results = this.formatResults(response.data.data);
          item.expanded = true; // 自动展开完成的结果
        } else {
          throw new Error(response.data.message || '审查失败');
        }
      } catch (error) {
        item.status = 'error';
        item.error = error.message || '审查过程中出现错误';
      } finally {
        this.stopProgressSimulation(item);
      }
    },

    // 开始进度条模拟
    startProgressSimulation(item) {
      if (this.progressIntervals[item.id]) {
        clearInterval(this.progressIntervals[item.id]);
      }

      this.progressIntervals[item.id] = setInterval(() => {
        if (item.progress < 90) {
          item.progress += Math.random() * 3;
        }
      }, 1000);
    },

    // 停止进度条模拟
    stopProgressSimulation(item) {
      if (this.progressIntervals[item.id]) {
        clearInterval(this.progressIntervals[item.id]);
        delete this.progressIntervals[item.id];
      }
      item.progress = 100;
    },

    // 格式化审查结果
    formatResults(data) {
      // 根据实际接口返回数据结构进行处理
      return Array.isArray(data) ? data : [];
    },

    // 切换展开/收起状态
    toggleReviewItem(index) {
      if (this.reviewItems[index].status === 'completed') {
        this.reviewItems[index].expanded = !this.reviewItems[index].expanded;
      }
    },

    // 重试审查
    retryReview(index) {
      const item = this.reviewItems[index];
      item.status = 'loading';
      item.progress = 0;
      item.error = null;
      
      this.startProgressSimulation(item);
      
      // 重新发起该项的审查请求
      this.checkContract(item, {
        fileUrl: this.$route.query.fileUrl,
        userId: localStorage.getItem('userId') || 'abc-1244',
        standpoint: this.$route.query.standpoint || '甲方',
        reviewScale: this.$route.query.reviewScale || '强',
        riskId: item.id
      });
    },

    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 'completed': return 'success';
        case 'loading': return 'warning';
        case 'error': return 'danger';
        default: return 'info';
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'completed': return '已完成';
        case 'loading': return '分析中';
        case 'error': return '出错';
        default: return '待审查';
      }
    },

    // 获取风险等级样式
    getRiskLevelClass(level) {
      return `risk-level-${level.toLowerCase()}`;
    }
  },
  
  beforeDestroy() {
    // 清理所有进度条定时器
    Object.values(this.progressIntervals).forEach(interval => {
      clearInterval(interval);
    });
  }
}
</script>

<style lang="scss" scoped>
.contract-review {
  padding: 20px;

  .review-results {
    margin-bottom: 20px;
  }

  .review-item {
    margin-bottom: 16px;
    border: 1px solid #EBEEF5;
    border-radius: 4px;
    overflow: hidden;
  }

  .review-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 20px;
    background-color: #F5F7FA;
    cursor: pointer;

    &:hover {
      background-color: #EBEEF5;
    }
  }

  .review-title {
    display: flex;
    align-items: center;
    gap: 12px;

    .el-tag {
      margin-left: 8px;
    }
  }

  .review-loading {
    padding: 30px;
    text-align: center;

    .loading-text {
      display: block;
      margin-top: 12px;
      color: #909399;
    }
  }

  .review-content {
    padding: 20px;
  }

  .review-detail {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    padding: 16px;
    background-color: #F8F9FA;
    border-radius: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .risk-level {
    padding: 4px 12px;
    border-radius: 4px;
    font-weight: bold;
    text-align: center;
    min-width: 80px;

    &.risk-level-high {
      background-color: #FEF0F0;
      color: #F56C6C;
    }

    &.risk-level-medium {
      background-color: #FDF6EC;
      color: #E6A23C;
    }

    &.risk-level-low {
      background-color: #F0F9EB;
      color: #67C23A;
    }
  }

  .risk-content {
    flex: 1;

    .risk-title {
      font-weight: bold;
      margin-bottom: 8px;
    }

    .risk-description {
      color: #606266;
      margin-bottom: 12px;
      line-height: 1.5;
    }

    .risk-suggestion {
      .label {
        color: #909399;
        margin-right: 8px;
      }

      .text {
        color: #409EFF;
      }
    }
  }

  .review-error {
    padding: 20px;
    text-align: center;
    color: #F56C6C;

    i {
      margin-right: 8px;
    }

    .el-button {
      margin-left: 12px;
    }
  }

  .review-actions {
    text-align: center;
    margin-top: 20px;
  }
}
</style> 